package com.example.handler_runnable_message;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {
    ProgressBar bar=null;
    Button startButton=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bar=(ProgressBar) findViewById(R.id.bar);
        startButton=(Button) findViewById(R.id.start);
        startButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bar.setVisibility(View.VISIBLE);
                updateBarHandler.post(updateThread);
            }
        });
    }
    Handler updateBarHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            bar.setProgress(msg.arg1);
        }
    };
    Runnable updateThread=new Runnable() {
        int i=0;
        @Override
        public void run() {
            System.out.println("Begin Thread");
            i=i+10;
            //新建updateBarHandler的Message对象
            Message msg=updateBarHandler.obtainMessage();
            msg.arg1=i;
            updateBarHandler.sendMessage(msg);
            if(i==100){
                i=0;
                bar.setProgress(0);
                updateBarHandler.removeCallbacks(updateThread);
            }else{updateBarHandler.postDelayed(updateThread,1000);}
            //进度条进度持续增加
        }
    };
}
